#include "TextToPcm.h"
#include <iostream>
#include <thread>

using namespace std;

TextToPcm::TextToPcm() {}

TextToPcm::~TextToPcm() {}

string TextToPcm::execPython(const std::string& cmd) {
    std::array<char, 256> buffer{};
    std::string result;

    // 打开管道，执行命令
    std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd.c_str(), "r"), pclose);
    if (!pipe) {
        throw std::runtime_error("popen() failed!");
    }

    // 读取输出
    while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
        result += buffer.data();
    }

    return result;
}

string TextToPcm::get_model_response(string input_text) {
    // 注意确保Python环境可用
    std::string pythonCmd = "python3 ../src/texttopcm/texttopcm.py"; //注意路径，这个路径是从build目录看的  // "pwd"
    std::string output;
    try {
        output = execPython(pythonCmd + " \"" + input_text + "\"");

        // 因为你的脚本最后 print 了一行，所以输出就是你想要的字符串
        // std::cout << "Python脚本输出内容:\n" << output << std::endl;
    } catch (const std::exception& ex) {
        std::cerr << "执行Python脚本失败: " << ex.what() << std::endl;
    }
    return output;
}